package com.app.util;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSON;

public class ResultUtil {

    /**
     * jsonp数据
     * 
     * @param request
     * @param reponse
     * @param data 从后台获得的数据
     */
    public static void jsonp(HttpServletRequest request, HttpServletResponse response, Object data) {
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        String callback = request.getParameter("callback");
        if (StringUtils.isNoneBlank(callback)) {
            if (data == null) {
                callback += "()";
            } else {
                callback += "(" + JSON.toJSONString(data) + ")";
            }
        } else {
            callback = JSON.toJSONString(data);
        }
        try {
            response.getWriter().print(callback);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
